package com.phcx.corporate.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.phcx.corporate.model.AdminInfo;
import com.phcx.corporate.model.BizLog;
import com.phcx.corporate.model.BizRecord;
import com.phcx.corporate.model.Result;
import com.phcx.corporate.service.BizLogService;
import com.phcx.corporate.service.BizRecordService;
import com.phcx.corporate.utils.SessionUtil;
import com.phcx.corporate.utils.TableUtil;
import com.phcx.corporate.vo.BizRecordInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/*
 * @Author: zmh
 * @Date: 2023/05/23/9:23
 * @Description: 打印日志插入、日志查询范围的限制
 */
@Slf4j
@RestController
@RequestMapping("/biz")
public class BizController {

    @Autowired
    private BizRecordService bizRecordService;

    @Autowired
    private BizLogService bizLogService;

    /**
     *  查询打印企业码日志
     *
     *  超管：所有记录
     *  管理员：自己及所在单位其他操作员记录
     *  操作员：自己记录
     */
    @RequestMapping("/findBizList/{current}/{limit}")
    public Result<Page<BizRecord>> findAll(@PathVariable Integer current, @PathVariable("limit") Integer size,
                                           @RequestBody BizRecordInfoVo queryVo,
                                           HttpServletRequest request) {
        AdminInfo adminInfo1 = SessionUtil.sessionExpiration(request);
        if (adminInfo1 == null){
            return Result.fail();
        }

        log.info("[查询打印记录]");
        Page<BizRecord> result = null;

        try {
            AdminInfo admin = (AdminInfo) request.getSession().getAttribute("admin");
            String accountType = admin.getAccountType();
            Page<BizRecord> page = new Page<>(current, size);
            LambdaQueryWrapper<BizRecord> wrapper = new LambdaQueryWrapper<>();
            if("0".equals(accountType)){
                wrapper.eq(BizRecord::getAdminId, admin.getAdminId())
                        .like(!StringUtils.isEmpty(queryVo.getLicence18()),BizRecord::getLicence18,queryVo.getLicence18())
                        .eq(!StringUtils.isEmpty(queryVo.getLicence13()),BizRecord::getLicence13,queryVo.getLicence13())
                        .orderByDesc(BizRecord::getLogDate);
                result = bizRecordService.page(page, wrapper);
            }else if("1".equals(accountType)){
                if("411300".equals(admin.getLicence42Code())){
                    wrapper.orderByDesc(BizRecord::getLogDate)
                            .like(!StringUtils.isEmpty(queryVo.getLicence18()),BizRecord::getLicence18,queryVo.getLicence18())
                            .eq(!StringUtils.isEmpty(queryVo.getLicence13()),BizRecord::getLicence13,queryVo.getLicence13());
                    result = bizRecordService.page(page, wrapper);
                }else{
//                    wrapper.select("biz_id", "biz_type", "admin_id", "username", "licence_18", "licence_13", "log_date")
//                            .apply("SUBSTR(licence_13, 3, 6) = {0}", admin.getLicence42Code())
//                            .orderByDesc("log_date");
                    wrapper.select(BizRecord::getBizId, BizRecord::getBizType, BizRecord::getAdminId, BizRecord::getUsername, BizRecord::getLicence18, BizRecord::getLicence13, BizRecord::getLogDate)
                            .like(!StringUtils.isEmpty(queryVo.getLicence18()),BizRecord::getLicence18,queryVo.getLicence18())
                            .eq(!StringUtils.isEmpty(queryVo.getLicence13()),BizRecord::getLicence13,queryVo.getLicence13())
                            .apply("SUBSTR(licence_13, 3, 6) = {0}", admin.getLicence42Code())
                            .orderByDesc(BizRecord::getLogDate);
                    result = bizRecordService.page(page, wrapper);
                }
            }else if ("2".equals(accountType)) {
                wrapper.orderByDesc(BizRecord::getLogDate)
                        .like(!StringUtils.isEmpty(queryVo.getLicence18()),BizRecord::getLicence18,queryVo.getLicence18())
                        .eq(!StringUtils.isEmpty(queryVo.getLicence13()),BizRecord::getLicence13,queryVo.getLicence13());
                result = bizRecordService.page(page, wrapper);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.ok(result);
    }


    /**
     *  插入打印日志
     */
    @RequestMapping("/insertBizRecord/{orgcode}/{entName}")
    public Result<?> insertOne(@PathVariable String orgcode, @PathVariable String entName, HttpServletRequest request) {

        AdminInfo adminInfo1 = SessionUtil.sessionExpiration(request);
        if (adminInfo1 == null){
            return Result.fail();
        }

        String bizLogId = (String) request.getSession().getAttribute("bizLogId");
        String newBizLogId = TableUtil.getID();

        if(bizLogId != null){
            log.info("[插入打印日志]");
            BizLog bizLog = bizLogService.getById(bizLogId);
            if(bizLog.getBizType().equals("0")){
                bizLog.setBizType("1");
                bizLogService.updateById(bizLog);
            }else if(bizLog.getBizType().equals("1")){
                bizLog.setLogId(newBizLogId);
                bizLogService.save(bizLog);
            }

        }

        log.info("[插入打印记录]");
        AdminInfo admin = (AdminInfo) request.getSession().getAttribute("admin");
        try {
            BizRecord bizRecord = BizRecord.builder()
                    .bizId(newBizLogId)
                    .bizType("1")
                    .adminId(admin.getAdminId())
                    .username(admin.getUsername())
                    .licence18(entName)
                    .licence13(orgcode)
                    .logDate(TableUtil.getLogTime()).build();

            bizRecordService.save(bizRecord);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Result.ok();

    }
}
